package lock;

/*
HashSet线程不安全的演示以及解决方案
 */

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

public class ThreadDemo5 {

  public static void main(String[] args) {

//    Set<String> set = new HashSet<>();

//    解决:使用CopyOnWriteArraySet解决，兼顾并发读，独立写操作
    Set<String> set = new CopyOnWriteArraySet<>();

    for (int i = 0; i < 30; i++) {

      new Thread(new Runnable() {
        @Override
        public void run() {
          set.add(UUID.randomUUID().toString().substring(0,8));
          System.out.println(set);
        }
      },String.valueOf(i)).start();

    }

  }
}
